package com.sdry.web.controller.jyy;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sdry.model.barCodeOperation.BarCodeOperation;
import com.sdry.model.jyy.ErrorJyy;
import com.sdry.model.jyy.Receive;
import com.sdry.model.jyy.ReceiveDetail;
import com.sdry.model.jyy.ReceiveDetailQuality;
import com.sdry.model.jyy.Up;
import com.sdry.model.jyy.Workload;
import com.sdry.model.llm.DevaningLog;
import com.sdry.model.llm.DevaningWork;
import com.sdry.model.llm.LlmWarehouseStock;
import com.sdry.model.lz.BarCodeConversionRecord;
import com.sdry.model.lz.CodeMark;
import com.sdry.model.lz.Customer;
import com.sdry.model.lz.LzQueryCriteria;
import com.sdry.model.lz.Materiel;
import com.sdry.model.lz.ReceiveMark;
import com.sdry.model.tdd.emailRecord.EmailRecord;
import com.sdry.model.zc.ZcGeneralQueryEntity;
import com.sdry.model.zc.ZcInventoryInfoEntity;
import com.sdry.model.zc.ZcMaterielAndTrayEntity;
import com.sdry.model.zc.ZcTrayAndLocationEntity;
import com.sdry.service.barCodeOperation.BarCodeOperationService;
import com.sdry.service.jyy.ErrorServise;
import com.sdry.service.jyy.ReceiveDetailService;
import com.sdry.service.jyy.ReceiveService;
import com.sdry.service.jyy.UpService;
import com.sdry.service.jyy.unpack.UnpackDetalService;
import com.sdry.service.llm.CancellingStockDetailService;
import com.sdry.service.llm.DevaningWorkService;
import com.sdry.service.llm.InquiryBusinessService;
import com.sdry.service.lz.InventoryService;
import com.sdry.service.lz.MaterielService;
import com.sdry.service.lz.StockOutOrderService;
import com.sdry.service.tdd.UnpackingService;
import com.sdry.service.tdd.emailRecord.EmailRecordService;
import com.sdry.service.zc.ZcBindAndUnbindService;
import com.sdry.service.zc.ZcInventoryManagementService;
import com.sdry.service.zc.ZcSimplificationInService;
import com.sdry.utils.DateUtil;
import com.sdry.utils.ResponseUtil;

/**
 * 收货和入库的app接口
 * @author jyy
 * @2019-05-16 14:15:38
 */
@RequestMapping("/app")
@Controller
public class AppJyController {
	@Resource ReceiveService ReceiveService;
	@Resource ReceiveDetailService ReceiveDetailService;
	@Resource InquiryBusinessService inquiryBusinessService;
	@Resource UpService upService;
	@Resource ZcInventoryManagementService zcInventoryManagementService;
	@Resource UnpackingService unpackingService;
	@Resource MaterielService materielService;
	@Resource ZcBindAndUnbindService zcBindAndUnbindService;
	@Resource CancellingStockDetailService cancellingStockDetailService;
	@Resource DevaningWorkService devaningWorkService;
	@Resource ZcSimplificationInService zcSimplificationInService;
	@Resource BarCodeOperationService barCodeOperationService;
	@Resource InventoryService inventoryService;
	@Resource StockOutOrderService stockOutService;
	@Resource UnpackDetalService unpackDetalService;
	@Resource ErrorServise errorServise;
	@Resource EmailRecordService emailRecordService;
	
	//计数循环次数	
	//int count;
	/**
	 * 给app查询所有未收货的收货单
	 * @param response 
	 * @throws Exception
	 */
	@RequestMapping("/selectAllReceive")
	public void selectAllReceive(HttpServletResponse response) throws Exception {
		Receive param = new Receive();
		//未收货
		param.setState(0);
		List<Receive> list = ReceiveService.queryAllByMution(param);
		
		JSONObject jsonObject = new JSONObject();
		int count = list.size();
		if (count>0) {
			//传递数据到页面
		    jsonObject.put("status", "1");
		    jsonObject.put("message", "");
		    jsonObject.put("data", list);
		}else {
			//传递数据到页面
		    jsonObject.put("status", "0");
		    jsonObject.put("message", "查询数据为空");
		    jsonObject.put("data", list);
		}
		ResponseUtil.write(response, jsonObject);
	}
	
	/**
	 * 根据收货单号查询收货详情
	 * @param receiveNumber 收货单号
	 * @param response 响应
	 * @throws Exception 
	 */
	@RequestMapping("/selectReceiveDtailByNumber")
	public void selectReceiveDtailByNumber(String receiveNumber,HttpServletResponse response) throws Exception {
		
		ReceiveDetail param = new ReceiveDetail();
		param.setReceiveNumber(receiveNumber);
		List<ReceiveDetail> list = ReceiveDetailService.queryAllByMution(param );
		
		JSONObject jsonObject = new JSONObject();
		int count = list.size();
		if (count > 0) {
			//传递数据到页面
		    jsonObject.put("status", "1");
		    jsonObject.put("message", "");
		    jsonObject.put("data", list);
		}else {
			//传递数据到页面
		    jsonObject.put("status", "0");
		    jsonObject.put("message", "查询数据为空");
		    jsonObject.put("data", list);
		}
		ResponseUtil.write(response, jsonObject);
	}
	
	/**
	 * 1.收货提交
	 * @param Details 收货详情集合
	 * @param person 收货人
	 * @param sure_name 回收容器数量
	 * @param response 响应
	 * @throws Exception 异常
	 */
	//TODO
	@RequestMapping("/submitReceive")
	public void submitReceive(String Details, String person, String sure_name, List<MultipartFile> pic_key, HttpServletResponse response, HttpSession session) {
		//计数循环次数
		int count = 0;
		String imgLog = "";
		if(pic_key.size() > 0){
			for(MultipartFile f : pic_key){
				if(f != null){
					// 1.获取原文件名1
					String oriName = f.getOriginalFilename();
					// 2.获取原文件图片后缀，以最后的.作为截取(.jpg)1
					String extName = oriName.substring(oriName.lastIndexOf("."));
					// 3.生成自定义的新文件名，这里以UUID.jpg|png|xxx作为格式（可选操作，也可以不自定义新文件名）1
					String uuid = UUID.randomUUID().toString();
					//组合成新的文件
					String newName = uuid + extName;
					// 4.获取要保存的路径文件夹1
					String realPath = session.getServletContext().getRealPath("/images/");
					// 5.保存1
					String savePath = realPath + "\\" +  newName;
					imgLog = "/images/" + newName;
					File desFile = new File(savePath);
					try {
						f.transferTo(desFile);
					} catch (IllegalStateException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		String addStr = "";
		CodeMark codeMark = new CodeMark();
		int affact = 0;
		Gson gson = new Gson();
		//接收APP传过来的数据
		List<ReceiveDetail> receiveDetailList = gson.fromJson(Details, new TypeToken<List<ReceiveDetail>>() {}.getType());
		//遍历修改
		for (ReceiveDetail receiveDetail : receiveDetailList) {
			int number = 0;
			for (int i = 0; i < receiveDetail.getReceiveCode().size(); i++) {
				number += receiveDetail.getReceiveCode().get(i).getNum();
			}
			//根据物料id查询物料
			Materiel materiel = materielService.queryMaterielById(receiveDetail.getMid());
			//1、给条码库存写入数量
			int numbers = receiveDetail.getCodeNum();
			ZcInventoryInfoEntity zcInventoryInfoEntity = upService.selectByMid(receiveDetail.getMid() + "", receiveDetail.getPici());
			//先根据物料id和批次查询条码库存是否存在
			if (zcInventoryInfoEntity != null) {
				int mNum = zcInventoryInfoEntity.getmNum();
				mNum = number + mNum;
				//总数量（个数）
				zcInventoryInfoEntity.setmNum(mNum);
				Long affact1 = upService.editStock(zcInventoryInfoEntity);
				//如果库存大于或小于预警值  报警
				String content = "";
				if (materiel != null) {
					String materiel_num = materiel.getMateriel_num();
					//String materiel_name = materiel.getMateriel_name();
					//String people = "";
					if (zcInventoryInfoEntity.getmNum() >= materiel.getUpper_value()) {
						content = materiel_num + "库存" + zcInventoryInfoEntity.getmNum() + "大于等于" + materiel.getUpper_value() + "特此报警";
						//PushExample.testSendPush(content , "库存报警", people, "0");
					} else if (zcInventoryInfoEntity.getmNum() <= materiel.getLower_value()) {
						content = materiel_num + "库存" + zcInventoryInfoEntity.getmNum() + "低于等于" + materiel.getLower_value() + "特此报警";
						//PushExample.testSendPush(content , "库存报警", people, "0");
					}
				}
				//2、邮件推送
				//根据供应商id查询供应商的邮箱
				Customer customer = upService.queryCustomerEmailById(materiel.getCustomer_id());
				if (customer != null && !"".equals(content)) {
					EmailRecord emailRecord = new EmailRecord();
					emailRecord.setOperate("入库");
					emailRecord.setReceivePeopleId(customer.getId());
					emailRecord.setReceiveDate(DateUtil.dateFormat3());
					emailRecord.setEmailContent(content);
					emailRecord.setRemark("0");
					emailRecordService.insert(emailRecord);
				}
			} else {
				//先根据物料id和批次查询条码库存是否存在,没有查到
				ZcInventoryInfoEntity zcInventoryInfoEntity1 = new ZcInventoryInfoEntity();
				zcInventoryInfoEntity1.setMid(receiveDetail.getMid());
				zcInventoryInfoEntity1.setmNum(receiveDetail.getCodeNum());
				zcInventoryInfoEntity1.setmBatch(receiveDetail.getPici());
				zcInventoryInfoEntity1.setEnterPerson(Long.parseLong(person));
				Long affact2 = upService.insertStock(zcInventoryInfoEntity1);
				//如果库存大于或小于预警值  报警
				String content = "";
				if (materiel != null) {
					String materiel_num = materiel.getMateriel_num();
					String materiel_name = materiel.getMateriel_name();
					String people = "";
					if (zcInventoryInfoEntity1.getmNum() >= materiel.getUpper_value()) {
						content = materiel_num + "库存" + zcInventoryInfoEntity1.getmNum() + "大于等于" + materiel.getUpper_value() + "特此报警";
						//PushExample.testSendPush(content , "库存报警", people, "0");
					} else if (zcInventoryInfoEntity1.getmNum() <= materiel.getLower_value()) {
						content = materiel_num + "库存" + zcInventoryInfoEntity1.getmNum() + "低于等于" + materiel.getLower_value() + "特此报警";
						//PushExample.testSendPush(content , "库存报警", people, "0");
					}
				}
				//2、邮件推送
				//根据供应商id查询供应商的邮箱
				Customer customer = upService.queryCustomerEmailById(materiel.getCustomer_id());
				if (customer != null && !"".equals(content)) {
					EmailRecord emailRecord = new EmailRecord();
					emailRecord.setOperate("入库");
					emailRecord.setReceivePeopleId(customer.getId());
					emailRecord.setReceiveDate(DateUtil.dateFormat3());
					emailRecord.setEmailContent(content);
					emailRecord.setRemark("0");
					emailRecordService.insert(emailRecord);
				}
			}
			//3、判断是否质检（质检表添加信息,将自增主键填写进去，修改时使用；先判断是否第一次有提交收货总数为零的，如果没有才能进入质检表）
			int sum = 0;
			for (int i = 0; i < receiveDetail.getReceiveCode().size(); i++) {
				sum += receiveDetail.getReceiveCode().get(i).getNum();
			}
			if (sum > 0) {
				//如果不质检
				if (materiel.getIs_check() == 1) {
					receiveDetail.setCodeNum(sum);
					receiveDetail.setRemark(receiveDetail.getId() + "");
					receiveDetail.setStatus(1);
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					receiveDetail.setCheck_date(sdf.format(new Date()));
					Long indentity1 = ReceiveDetailService.addReceiveDetailQuality1(receiveDetail);
					//4、给CodeMark绑定条码
					for (int j = 0; j < receiveDetail.getReceiveCode().size(); j++) {
						codeMark = new CodeMark();
						codeMark.setReceive_detail_id(indentity1);
						codeMark.setCode(receiveDetail.getReceiveCode().get(j).getCode());
						codeMark.setNum(receiveDetail.getReceiveCode().get(j).getNum());
						codeMark.setIs_ng(receiveDetail.getReceiveCode().get(j).getIs_ng());
						ReceiveDetailService.addCodeMark(codeMark);
						addStr += receiveDetail.getReceiveCode().get(j).getCode() + ",";
						//5、给历史记录表插入数据
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						String time = format.format(new Date());
						BarCodeOperation bar = new BarCodeOperation();
						bar.setBarCode(receiveDetail.getReceiveCode().get(j).getCode());
						bar.setBatch(receiveDetail.getPici());
						bar.setOperator(Long.parseLong(person));
						bar.setOperatingTime(time);
						bar.setMaterielId(receiveDetail.getMid());
						bar.setType("质检");
						bar.setResult("成功");
						barCodeOperationService.insert(bar);
					}
				} else {
					//如果质检
					receiveDetail.setCodeNum(sum);
					receiveDetail.setRemark(receiveDetail.getId() + "");
					receiveDetail.setStatus(0);
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					receiveDetail.setCheck_date(sdf.format(new Date()));
					Long indentity2 = ReceiveDetailService.addReceiveDetailQuality(receiveDetail);
					//4、给CodeMark绑定条码
					for (int j = 0; j < receiveDetail.getReceiveCode().size(); j++) {
						codeMark = new CodeMark();
						codeMark.setReceive_detail_id(indentity2);
						codeMark.setCode(receiveDetail.getReceiveCode().get(j).getCode());
						codeMark.setNum(receiveDetail.getReceiveCode().get(j).getNum());
						codeMark.setIs_ng(receiveDetail.getReceiveCode().get(j).getIs_ng());
						ReceiveDetailService.addCodeMark(codeMark);
						addStr += receiveDetail.getReceiveCode().get(j).getCode() + ",";
						//5、给历史记录表插入数据
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						String time = format.format(new Date());
						BarCodeOperation bar = new BarCodeOperation();
						bar.setBarCode(receiveDetail.getReceiveCode().get(j).getCode());
						bar.setBatch(receiveDetail.getPici());
						bar.setOperator(Long.parseLong(person));
						bar.setOperatingTime(time);
						bar.setMaterielId(receiveDetail.getMid());
						bar.setType("质检");
						bar.setResult("成功");
						barCodeOperationService.insert(bar);
					}
				}
			}
			//6、修改收货详细表信息
			receiveDetail.setCodeNum(numbers);
			affact = ReceiveDetailService.update(receiveDetail);
			//遍历看发货数量和收货数量是否匹配，匹配上则修改收货单状态，匹配不上则不改状态
			if (receiveDetail.getTotalNum() == receiveDetail.getCodeNum()) {
				count ++;
			}
		}
		//7、到质检区
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = new ZcMaterielAndTrayEntity();
		String tray_code = System.currentTimeMillis()+"";
		zcMaterielAndTrayEntity.setTray_code(tray_code);
		zcMaterielAndTrayEntity.setMateriel_code(addStr);
		zcMaterielAndTrayEntity.setBinding_person(Long.parseLong(person));
		zcMaterielAndTrayEntity.setBinding_date(sdf.format(date));
		zcMaterielAndTrayEntity.setTargetRegion("待检区");
		//zcMaterielAndTrayEntity.setLocation_code(location_code);
		int affact2 = zcBindAndUnbindService.bindAndUp2SpecialArea(zcMaterielAndTrayEntity);
		//8、更改收货单状态为已收货
		ReceiveDetail receiveDetail = receiveDetailList.get(0);
		Receive receive = new Receive();
		receive.setReceiveNumber(receiveDetail.getReceiveNumber());
		List<Receive> receives = ReceiveService.queryAllByMution(receive);
		JSONObject jsonObject = new JSONObject();
		//9、如果每条记录都匹配，则修改状态
		if (count == receiveDetailList.size()) {
			//获取收货单号
			Receive receive2 = receives.get(0);
			receive2.setState(1);
			receive2.setReceiveDate(DateUtil.dateFormat3());
			receive2.setReceiveName(person);
			//回收容器数量
			receive2.setSureName(sure_name);
			receive2.setImgLog(imgLog);
			ReceiveService.update(receive2);
		} else {
			//获取收货单号
			Receive receive2 = receives.get(0);
			receive2.setReceiveDate(DateUtil.dateFormat3());
			receive2.setReceiveName(person);
			//回收容器数量
			receive2.setSureName(sure_name);
			receive2.setImgLog(imgLog);
			ReceiveService.update(receive2);
		}
		//10、给历史记录表插入数据
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for(ReceiveDetail detail : receiveDetailList){
			BarCodeOperation bar = new BarCodeOperation();
			bar.setBatch(detail.getPici());
			bar.setOperator(Long.parseLong(person));
			bar.setOperatingTime(sdf2.format(date));
			bar.setMaterielId(detail.getMid());
			bar.setType("收货");
			if(affact > 0){
				bar.setResult("成功");
			} else {
				bar.setResult("失败");
			}
			for(CodeMark cm : detail.getReceiveCode()){
				bar.setBarCode(cm.getCode());
				barCodeOperationService.insert(bar);
			}
		}
		if(affact > 0) {
			//传递数据到页面
		    jsonObject.put("status", "1");
		    jsonObject.put("message", "");
		    jsonObject.put("data", "提交成功");
		} else {
			//传递数据到页面
		    jsonObject.put("status", "0");
		    jsonObject.put("message", "提交失败");
		    jsonObject.put("data", "0");
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据物料产品码查询物料所有信息
	 * @param maNum 物料产品码
	 * @param response 响应
	 * @throws Exception 
	 */
	/*@RequestMapping("/selectMaByMaNum")
	public void selectMaByMaNum(String maNum, HttpServletResponse response) throws Exception {
		Materiel materiel = ReceiveService.selectMaByMaNum(maNum);
		if(materiel != null) {
			if(materiel.getId() != null) {
				List<Customer> customers = ReceiveService.selectCustomerByMid(materiel.getId());
				
				if(customers.size() > 0) {
					materiel.setCustomer(customers);
				}
			}
		}
		JSONObject jsonObject = new JSONObject();
		if (materiel != null) {
			//传递数据到页面
		    jsonObject.put("status", "1");
		    jsonObject.put("message", "");
		    jsonObject.put("data", materiel);
		}else {
			//传递数据到页面
		    jsonObject.put("status", "0");
		    jsonObject.put("message", "查询数据不存在");
		    jsonObject.put("data", materiel);
		}
		ResponseUtil.write(response, jsonObject);
	}*/
	
	/**
	 * 根据物料id查询，存放该物料的仓库、库区、库位信息
	 * @param mid 物料id
	 * @param response 响应
	 * @throws Exception 
	 */
	@RequestMapping("/selectWarehouseByMid")
	public void selectWarehouseByMid(String mid, String customer, HttpServletResponse response) throws Exception {
		
		Up up = new Up();
		//物料id
		if(mid != null && mid != "") {
			up.setMid(Long.valueOf(mid));
		}
		//供应商id
		if(customer != null) {
			up.setCustomerId(Long.valueOf(customer));
		}
		List<LlmWarehouseStock> list = new ArrayList<LlmWarehouseStock>();
		
		if(mid != null && mid != "") {
			list = ReceiveService.selectWarehouseByMid(up);
		}else {
			list = inquiryBusinessService.appGetStock();
		}
		
		JSONObject jsonObject = new JSONObject();
		int count = list.size();
		if (count > 0) {
			//传递数据到页面
		    jsonObject.put("status", "1");
		    jsonObject.put("message", "");
		    jsonObject.put("data", list);
		}else {
			//传递数据到页面
		    jsonObject.put("status", "0");
		    jsonObject.put("message", "查询数据为空");
		    jsonObject.put("data", list);
		}
		ResponseUtil.write(response, jsonObject);
	}
	
	
	/**
	 * 质检后的条码绑定
	 * @param json 质检后的条码绑定
	 * @param response
	 * @throws Exception 
	 */
	@RequestMapping("/comeku")
	public void comeku(String json, String person, HttpServletResponse response) {
		String addStr = "";
		Long affact = 0L;
		Gson gson = new Gson();
		List<ReceiveDetailQuality> receiveDetailQualityList = gson.fromJson(json, new TypeToken<List<ReceiveDetailQuality>>() {}.getType());
		for (ReceiveDetailQuality receiveDetailQuality : receiveDetailQualityList) {
			for (int j = 0; j < receiveDetailQuality.getReceiveCode().size(); j++) {
				CodeMark exitCodeMark = ReceiveDetailService.queryCodeMarkByCode(receiveDetailQuality.getReceiveCode().get(j));
				if (exitCodeMark != null) {
					//根据精准码修改质检区库存的数量
					/*ReceiveDetailService.updateInventoryInfoQuality(receiveDetailQuality.getMid() + "", 
							receiveDetailQuality.getPici(), (exitCodeMark.getNum() - receiveDetailQuality.getReceiveCode().get(j).getNum()) + "");*/
					CodeMark codeMark = new CodeMark();
					codeMark.setCode(exitCodeMark.getCode());
					codeMark.setNum(receiveDetailQuality.getReceiveCode().get(j).getNum());
					//传入查询到的条码和提交的数量
					affact = ReceiveDetailService.updateCodeMark(codeMark);
				} else {
					CodeMark codeMark = new CodeMark();
					codeMark.setReceive_detail_id(receiveDetailQuality.getId());
					codeMark.setCode(receiveDetailQuality.getReceiveCode().get(j).getCode());
					codeMark.setNum(receiveDetailQuality.getReceiveCode().get(j).getNum());
					codeMark.setIs_ng(receiveDetailQuality.getReceiveCode().get(j).getIs_ng());
					//添加每种物料对应的多个条码
					ReceiveDetailService.addCodeMark(receiveDetailQuality.getReceiveCode().get(j));
					addStr += receiveDetailQuality.getReceiveCode().get(j).getCode() + ",";
				}
				//绑定后修改质检的状态为2
				ReceiveDetailService.updateReceiveDetailQuality2(receiveDetailQuality.getId() + "");
				//拆箱
				//ReceiveDetailService.uncomeku(code);
			}
		}
		//质检后同步质检区
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = new ZcMaterielAndTrayEntity();
		zcMaterielAndTrayEntity.setMateriel_code(addStr);
		zcMaterielAndTrayEntity.setBinding_person(Long.parseLong(person));
		zcMaterielAndTrayEntity.setBinding_date(sdf.format(date));
		zcMaterielAndTrayEntity.setTargetRegion("待检区");
		//zcMaterielAndTrayEntity.setTray_code(tray_code);
		//zcMaterielAndTrayEntity.setLocation_code(location_code);
		int affact2 = zcBindAndUnbindService.bindAndUp2SpecialArea(zcMaterielAndTrayEntity);
		JSONObject jsonObject = new JSONObject();
		if (affact > 0) {
			//传递数据到页面
			jsonObject.put("status", "1");
			jsonObject.put("message", "");
			jsonObject.put("data", "提交成功");
		} else {
			//传递数据到页面
			jsonObject.put("status", "0");
			jsonObject.put("message", "提交失败");
			jsonObject.put("data", "0");
		}
		
		//----------------------给历史记录表插入数据   start-------------------------------------
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time = format.format(new Date());
		for (ReceiveDetailQuality receiveDetailQuality : receiveDetailQualityList) {
			for (int j = 0; j < receiveDetailQuality.getReceiveCode().size(); j++) {
				BarCodeOperation bar = new BarCodeOperation();
				bar.setBarCode(receiveDetailQuality.getReceiveCode().get(j).getCode());
				bar.setBatch(receiveDetailQuality.getPici());
				bar.setOperator(Long.parseLong(person));
				bar.setOperatingTime(time);
				bar.setMaterielId(receiveDetailQuality.getMid());
				bar.setType("质检");
				if(affact > 0){
					bar.setResult("成功");
				} else {
					bar.setResult("失败");
				}
				barCodeOperationService.insert(bar);
			}
		}
		//----------------------给历史记录表插入数据   end-------------------------------------
				
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 拆箱校验
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/selectAccurateByCodeApp")
	public void selectAccurateByCodeApp(HttpServletResponse response, String mcode) {
		JSONObject jsonObject = new JSONObject();
		String location_code = zcBindAndUnbindService.selectByMaterielCode(mcode+",");
		if("SY".equals(location_code)){
			jsonObject.put("status", "0");
			jsonObject.put("message", "该条码在损溢区");
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			//根据mcode查询收货单详细
			CodeMark codeMark = ReceiveDetailService.queryReceiveDetailIdByMcode(mcode);
			if (codeMark != null) {
				List<ReceiveDetail> receiveDetailList = ReceiveDetailService.selectAccurateByCodeApp(codeMark.getReceive_detail_id());
				if (receiveDetailList.size() > 0) {
					ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = zcBindAndUnbindService.selectMaterielLocationByCodeDown(mcode);
					if(zcMaterielAndTrayEntity.getMateriel_code() != null && !"".equals(zcMaterielAndTrayEntity.getMateriel_code())){
						receiveDetailList.get(0).getReceiveCode().add(codeMark);
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "此物料未下架");
						jsonObject.put("data", receiveDetailList.get(0));
					} else {
						receiveDetailList.get(0).getReceiveCode().add(codeMark);
						//传递数据到页面
						jsonObject.put("status", "1");
						jsonObject.put("message", "此物料已下架");
						jsonObject.put("data", receiveDetailList.get(0));
					}
				} else {
					//传递数据到页面
					jsonObject.put("status", "0");
					jsonObject.put("message", "查询不到此条码");
					jsonObject.put("data", null);
				}
				try {
					ResponseUtil.write(response, jsonObject);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				//传递数据到页面
				jsonObject.put("status", "0");
				jsonObject.put("message", "查询不到此条码");
				jsonObject.put("data", null);
				try {
					ResponseUtil.write(response, jsonObject);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	/**
	 * 拆箱校验（新）
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/selectAccurateByCodeApp2")
	public void selectAccurateByCodeApp2(HttpServletResponse response, String mcode) {
		JSONObject jsonObject = new JSONObject();
		//根据mcode查询收货单详细
		CodeMark codeMark = ReceiveDetailService.queryReceiveDetailIdByMcode(mcode);
		if (codeMark != null) {
			List<ReceiveDetail> receiveDetailList = ReceiveDetailService.selectAccurateByCodeApp(codeMark.getReceive_detail_id());
			if (receiveDetailList.size() > 0) {
				ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = zcBindAndUnbindService.selectMaterielLocationByCodeDown(mcode);
				if(zcMaterielAndTrayEntity.getMateriel_code() != null && !"".equals(zcMaterielAndTrayEntity.getMateriel_code())){
					receiveDetailList.get(0).getReceiveCode().add(codeMark);
					//传递数据到页面
					jsonObject.put("status", "0");
					jsonObject.put("message", "此物料未下架");
					jsonObject.put("data", receiveDetailList.get(0));
				} else {
					
					//根据物料id查询最早的批次
					String oldPici = ReceiveDetailService.selectOldPiciByMid(receiveDetailList.get(0).getMid());
					receiveDetailList.get(0).setOldPici(oldPici);
					receiveDetailList.get(0).getReceiveCode().add(codeMark);
					//传递数据到页面
					jsonObject.put("status", "1");
					jsonObject.put("message", "此物料已下架");
					jsonObject.put("data", receiveDetailList.get(0));
				}
			} else {
				//传递数据到页面
				jsonObject.put("status", "0");
				jsonObject.put("message", "查询不到此条码");
				jsonObject.put("data", null);
			}
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			//传递数据到页面
			jsonObject.put("status", "0");
			jsonObject.put("message", "查询不到此条码");
			jsonObject.put("data", null);
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 根据条码查询状态（紧急收货单）
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/urgencySelectAccurateByCodeApp")
	public void urgencySelectAccurateByCodeApp(HttpServletResponse response, String mcode) {
		JSONObject jsonObject = new JSONObject();
		String location_code = zcBindAndUnbindService.selectByMaterielCode(mcode+",");
		if("SY".equals(location_code)){
			jsonObject.put("status", "0");
			jsonObject.put("message", "该条码在损溢区");
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			//根据mcode查询收货单详细
			CodeMark codeMark = ReceiveDetailService.queryReceiveDetailIdByMcode(mcode);
			if (codeMark != null) {
				List<ReceiveDetail> receiveDetailList = ReceiveDetailService.selectAccurateByCodeApp(codeMark.getReceive_detail_id());
				if (receiveDetailList.size() > 0) {
					if (1 == receiveDetailList.get(0).getStatus()) {
						ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = zcBindAndUnbindService.selectMaterielLocationByCodeDownLocation(mcode,"DJ");
						if(zcMaterielAndTrayEntity.getMateriel_code() != null && !"".equals(zcMaterielAndTrayEntity.getMateriel_code())){
							receiveDetailList.get(0).getReceiveCode().add(codeMark);
							//传递数据到页面
							jsonObject.put("status", "0");
							jsonObject.put("message", "质检区无此条码");
							//jsonObject.put("data", receiveDetailList.get(0));
						} else {
							receiveDetailList.get(0).getReceiveCode().add(codeMark);
							//传递数据到页面
							jsonObject.put("status", "1");
							//jsonObject.put("message", "此物料已下架");
							jsonObject.put("data", receiveDetailList.get(0));
						}
					}else if(0 == receiveDetailList.get(0).getStatus()){
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "此物料未质检");
						//jsonObject.put("data", null);
					}else{
						//传递数据到页面
						jsonObject.put("status", "0");
						jsonObject.put("message", "此物料已上架");
						//jsonObject.put("data", null);
					}
				} else {
					//传递数据到页面
					jsonObject.put("status", "0");
					jsonObject.put("message", "查询不到此条码");
					jsonObject.put("data", null);
				}
				try {
					ResponseUtil.write(response, jsonObject);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				//传递数据到页面
				jsonObject.put("status", "0");
				jsonObject.put("message", "查询不到此条码");
				jsonObject.put("data", null);
				try {
					ResponseUtil.write(response, jsonObject);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	/**
	 * 查询状态为1的收货单详细(盘点使用)
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/selectAccurateByCodeAppInventory")
	public void selectAccurateByCodeAppInventory(HttpServletResponse response, String mcode) {
		JSONObject jsonObject = new JSONObject();
		//根据mcode查询收货单详细
		CodeMark codeMark = ReceiveDetailService.queryReceiveDetailIdByMcode(mcode);
		if (codeMark != null) {
			List<ReceiveDetail> receiveDetailList = ReceiveDetailService.selectAccurateByCodeApp(codeMark.getReceive_detail_id());
			if (receiveDetailList.size() > 0) {
				receiveDetailList.get(0).getReceiveCode().add(codeMark);
				jsonObject.put("status", "1");
				jsonObject.put("data", receiveDetailList.get(0));
			} else {
				//传递数据到页面
				jsonObject.put("status", "0");
				jsonObject.put("message", "查询不到此条码");
				jsonObject.put("data", null);
			}
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			//传递数据到页面
			jsonObject.put("status", "0");
			jsonObject.put("message", "查询不到此条码");
			jsonObject.put("data", null);
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 查询状态为0的质检表
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/queryReceiveDetailQualityAPP")
	public void queryReceiveDetailQualityAPP(HttpServletResponse response) {
		CodeMark codeMark;
		JSONObject jsonObject = new JSONObject();
		//根据mcode查询收货单详细
		List<ReceiveDetailQuality> receiveDetailQualityList = ReceiveDetailService.queryReceiveDetailQualityAPP();
		for (int i = 0; i < receiveDetailQualityList.size(); i++) {
			List codeMarkList = new ArrayList<>();
			//List<CodeMark> codeMark1 = ReceiveDetailService.queryCodeMarkById(receiveDetailQualityList.get(i).getRemark());
			List<CodeMark> codeMark1 = ReceiveDetailService.queryCodeMarkById(receiveDetailQualityList.get(i).getId()+"");
			for (int j = 0; j < codeMark1.size(); j++) {
				codeMark = new CodeMark();
				codeMark.setReceive_detail_id(codeMark1.get(j).getReceive_detail_id());
				codeMark.setNum(codeMark1.get(j).getNum());
				codeMark.setCode(codeMark1.get(j).getCode());
				codeMark.setIs_ng(codeMark1.get(j).getIs_ng());
				codeMarkList.add(codeMark);
			}
			receiveDetailQualityList.get(i).setReceiveCode(codeMarkList);
		}
		if (receiveDetailQualityList.size() > 0) {
			jsonObject.put("status", "1");
			jsonObject.put("message", "");
			jsonObject.put("data", receiveDetailQualityList);
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "查询数据为空");
			jsonObject.put("data", null);
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 查询状态为1的质检表
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/queryReceiveDetailQualityAPP1")
	public void queryReceiveDetailQualityAPP1(HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();
		//根据mcode查询收货单详细
		List<ReceiveDetailQuality> receiveDetailQualityList = ReceiveDetailService.queryReceiveDetailQualityAPP1();
		if (receiveDetailQualityList.size() > 0) {
			jsonObject.put("status", "1");
			jsonObject.put("message", "");
			jsonObject.put("data", receiveDetailQualityList);
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "查询数据为空");
			jsonObject.put("data", null);
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 修改状态为0的质检表
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/updateReceiveDetailQualityAPP")
	public void updateReceiveDetailQualityAPP(String json, String person, HttpServletResponse response) {
		Long affactRow = 0L;
		Workload workload;
		//CodeMark codeMark;
		Gson gson = new Gson();
		List<ReceiveDetailQuality> receiveDetailQualityList = gson.fromJson(json, new TypeToken<List<ReceiveDetailQuality>>() {}.getType());
		//JSONObject jsonObject2 = JSONObject.fromObject(json);
		//ReceiveDetailQuality receiveDetailQuality = (ReceiveDetailQuality)JSONObject.toBean(jsonObject2, ReceiveDetailQuality.class);
		JSONObject jsonObject = new JSONObject();
		//根据receiveDetailQuality修改良品数和不良品数
		for (ReceiveDetailQuality receiveDetailQuality : receiveDetailQualityList) {
		//for (int i = 0; i < receiveDetailQualityList.size(); i++) {
			affactRow = ReceiveDetailService.updateReceiveDetailQualityAPP(receiveDetailQuality);
			//如果修改成功则给工作量实体添加数据
			for (int j = 0; j < receiveDetailQuality.getWorkloadList().size(); j++) {
				workload = new Workload();
				workload.setReceiveDetailQuality_id(receiveDetailQuality.getId());
				workload.setWorkman(receiveDetailQuality.getWorkloadList().get(j).getWorkman());
				workload.setGood_num(receiveDetailQuality.getWorkloadList().get(j).getGood_num());
				workload.setNgood_num(receiveDetailQuality.getWorkloadList().get(j).getNgood_num());
				//添加每种物料对应的工作量
				ReceiveDetailService.addWorkload(workload);
			}
			//现在条码
			List<CodeMark> codeMarkListX = receiveDetailQuality.getReceiveCode();
			//原有条码
			List<CodeMark> codeMarkListY = ReceiveDetailService.queryCodeMarkById(receiveDetailQuality.getId()+"");
			//现在条码比较原有条码新增
			List<CodeMark> codeMarkListXS = new ArrayList<>();
			//现在条码比较原有条码没有的
			List<CodeMark> codeMarkListYS = new ArrayList<>();
			
			for (int j = 0; j < codeMarkListY.size(); j++) {
				//在新条码中是否查询到此次循环旧条码 0 否 1是
				int flg = 0;
				for (int k = 0; k < codeMarkListX.size(); k++) {
					//此次循环新条码  == 此次循环旧条码
					if(codeMarkListX.get(k).getCode().equals(codeMarkListY.get(j).getCode())){
						//修改物料托盘信息
						ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = ReceiveDetailService.queryMaterielTrayByCode(codeMarkListY.get(j).getCode());
						if(zcMaterielAndTrayEntity != null){
							int num = zcMaterielAndTrayEntity.getmNum()-codeMarkListY.get(j).getNum()+codeMarkListX.get(k).getNum();
							inventoryService.updateById(zcMaterielAndTrayEntity.getId()+"", "mNum", num+"", "zc_materiel_tray");
						}
						//修改记录
						//根据精准码查询是否存在
						CodeMark CodeMark = ReceiveDetailService.queryCodeMarkByCode(codeMarkListY.get(j));
						if (CodeMark != null) {
							ReceiveDetailService.updateCodeMark(codeMarkListX.get(k));
						} else {
							//绑定新条码
							ReceiveDetailService.addCodeMark(codeMarkListX.get(k));
						}
						flg = 1;
						break;
					}
				}
				//没有找到
				if(flg == 0){
					//删除托盘物料
					ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = ReceiveDetailService.queryMaterielTrayByCode(codeMarkListY.get(j).getCode());
					if(zcMaterielAndTrayEntity != null){
						String mCode = zcMaterielAndTrayEntity.getMateriel_code();
						//用空字符串替换旧条码
						String newCode2 = mCode.replace(codeMarkListY.get(j).getCode()+",", "");
						if(newCode2.length() == 0){
							//如果托盘空了，则删除这条数据(现在不能删，只有添加新条码后，再盘点托盘为空，进行删除，新条码有可能放回来)
							ReceiveDetailService.deleteMaterielTrayById(zcMaterielAndTrayEntity.getId());
						}else{
							//把替换后的条码集合放回原来托盘
							ReceiveDetailService.updateMaterielTrayByCode(zcMaterielAndTrayEntity.getId() + "", newCode2);
							//根据精准码查询是否存在
							CodeMark codeMark = ReceiveDetailService.queryCodeMarkByCode(codeMarkListY.get(j));
							if (codeMark != null) {
								inventoryService.updateById(zcMaterielAndTrayEntity.getId()+"", "mNum", (zcMaterielAndTrayEntity.getmNum()-codeMark.getNum())+"", "zc_materiel_tray");
							} 
						}
					}
					//删除记录
					stockOutService.deleteCodemarkOutByCode(codeMarkListY.get(j).getCode());
				}
			}
			
			for (int j = 0; j < codeMarkListX.size(); j++) {
				//在新条码中是否查询到此次循环旧条码 0 否 1是
				int flg = 0;
				for (int k = 0; k < codeMarkListY.size(); k++) {
					if(codeMarkListX.get(j).getCode().equals(codeMarkListY.get(k).getCode())){
						flg = 1;
						break;
					}
				}
				if(flg == 0){
					codeMarkListXS.add(codeMarkListX.get(j));
				}
			}
			if(codeMarkListXS.size() > 0){
				String codes = "";
				int sum = 0;
				for (CodeMark codeMark : codeMarkListXS) {
					codes += codeMark.getCode() + ",";
					sum += codeMark.getNum();
					//绑定新条码
					ReceiveDetailService.addCodeMark(codeMark);
				}
				ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = new ZcMaterielAndTrayEntity();
				zcMaterielAndTrayEntity.setMid(receiveDetailQuality.getMid());
				zcMaterielAndTrayEntity.setmBatch(receiveDetailQuality.getPici());
				zcMaterielAndTrayEntity.setMateriel_code(codes);
				String tray_code = System.currentTimeMillis()+"";
				zcMaterielAndTrayEntity.setTray_code(tray_code);
				zcMaterielAndTrayEntity.setmNum(sum);
				zcMaterielAndTrayEntity.setBinding_person(Long.valueOf(person));;
				zcMaterielAndTrayEntity.setBinding_date(DateUtil.dateFormat1());;
				inventoryService.MaterielTrayInsert(zcMaterielAndTrayEntity);
				ZcTrayAndLocationEntity a = new ZcTrayAndLocationEntity();
				a.setLocation_code("DJ");
				ZcTrayAndLocationEntity zcTrayAndLocationEntityOld = zcBindAndUnbindService.selectTrayCodeByLocationCode(a);
				//3、如果不为空，修改数据
				if(zcTrayAndLocationEntityOld != null){
					String trayCodes = zcTrayAndLocationEntityOld.getTray_code() + zcMaterielAndTrayEntity.getTray_code() + ",";
					inventoryService.updateById(zcTrayAndLocationEntityOld.getId()+"", "tray_code", trayCodes, "zc_tray_location");
				}else{
					//4、新增库位至待检区
					ZcTrayAndLocationEntity zcTrayAndLocationEntity = new ZcTrayAndLocationEntity();
					//托盘码
					zcTrayAndLocationEntity.setTray_code(tray_code);
					//库区编码
					zcTrayAndLocationEntity.setLocation_code("DJ");
					//绑定人
					zcTrayAndLocationEntity.setBinding_person(zcMaterielAndTrayEntity.getBinding_person());
		    		//绑定时间
					zcTrayAndLocationEntity.setBinding_date(zcMaterielAndTrayEntity.getBinding_date());
					inventoryService.trayLocationInsert(zcTrayAndLocationEntity);
				}
			}
			
			/*//判断CodeMark是修改还是新增
			for (int k = 0; k < receiveCode.size(); k++) {
				//根据精准码查询是否存在
				CodeMark CodeMark = ReceiveDetailService.queryCodeMarkByCode(receiveCode.get(k));
				if (CodeMark != null) {
					ReceiveDetailService.updateCodeMark(receiveCode.get(k));
				} else {
					//绑定新条码
					ReceiveDetailService.addCodeMark(receiveCode.get(k));
				}
			}*/
			
			//给不良品库存添加数据,首先根据物料id和批次查询是否存在
			//TODO
			//int nowNum = receiveDetailQualityList.get(i).getNg_num();
			/**
			 * 根据批次和物料id查询不良品库是否存在该物料
			 */
			/*ZcRejectsWarehouseEntity zcRejectsWarehouseEntity = ReceiveDetailService.
					queryZcRejectsWarehouseEntityByMbatchAngMid(receiveDetailQualityList.get(i));
			//如果存在
			if (zcRejectsWarehouseEntity != null) {
				int totality = zcRejectsWarehouseEntity.getTotality();
				totality = nowNum + totality;
				receiveDetailQualityList.get(i).setNg_num(totality);
				ReceiveDetailService.updateZcRejectsWarehouseEntity(receiveDetailQualityList.get(i));
			} else {
				receiveDetailQualityList.get(i).setPerson(person);
				ReceiveDetailService.addZcRejectsWarehouseEntity(receiveDetailQualityList.get(i));
			}
			//将库存表中的不良品数量减掉
			ReceiveDetailService.updateInventoryInfoNum(receiveDetailQualityList.get(i));*/
		}
		if (affactRow > 0) {
			jsonObject.put("status", "1");
			jsonObject.put("message", "");
			jsonObject.put("data", "质检完成");
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "质检失败");
			jsonObject.put("data", "0");
		}
		
		//----------------------给历史记录表插入数据-------------------------------------
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time = format.format(new Date());
		for(ReceiveDetailQuality detail : receiveDetailQualityList){
			BarCodeOperation bar = new BarCodeOperation();
			bar.setBatch(detail.getPici());
			bar.setOperator(Long.parseLong(person));
			bar.setOperatingTime(time);
			bar.setMaterielId(detail.getMid());
			bar.setType("质检");
			if(affactRow > 0){
				bar.setResult("成功");
			}else{
				bar.setResult("失败");
			}
			for(CodeMark cm : detail.getReceiveCode()){
				bar.setBarCode(cm.getCode());
				barCodeOperationService.insert(bar);
			}
		}
		//----------------------给历史记录表插入数据-------------------------------------
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 拆箱
	 * @param json1
	 * @param json2
	 * @param userId
	 * @param response             
	 */
	@RequestMapping("/devanning")
	public void devanning(String json1, String json2, String userId, HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();
		Long identity = 0L;
		String codeArr1 = "";
		String codeArr2 = "";
		Gson gson = new Gson();
		//拆箱前
		List<CodeMark> codeMarkList1 = gson.fromJson(json1, new TypeToken<List<CodeMark>>() {}.getType());
		//拆箱后
		List<CodeMark> codeMarkList2 = gson.fromJson(json2, new TypeToken<List<CodeMark>>() {}.getType());
		//工作量
		List<Workload> workList = gson.fromJson(userId, new TypeToken<List<Workload>>() {}.getType());
		//删除缓存区
		/*for (CodeMark codeMark1 : codeMarkList1) {
			//codeArr1 += codeMark.getCode() + ",";
			//identity = ReceiveDetailService.updateMaterielTrayByCode1(codeMark.getCode());
			ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = ReceiveDetailService.queryMaterielTrayByCode(codeMark1.getCode()+",");
			//根据indentity查询新条码替换
			for (CodeMark codeMark2 : codeMarkList2) {
				//codeArr2 += codeMark.getCode() + ",";
				//addStr += codeMark.getCode() + ",";
				ReceiveDetailService.updateMaterielTrayByCode(zcMaterielAndTrayEntity.getId() + "", codeMark2.getCode()+",");
			}
		}*/
		
		//遍历查询是否有和剩余条码相同的条码
		int flag = 1;
		String codeArr3 = "";
		List<CodeMark> codeMarkList3 = materielService.queryAllCode(codeMarkList1.get(0).getCode());
		List<CodeMark> codeMarkList4 = new ArrayList<>();
		/*Iterator<CodeMark> iterator1 = codeMarkList1.iterator();
		Iterator<CodeMark> iterator2 = codeMarkList2.iterator();  
        while (iterator1.hasNext()) {  
        	CodeMark codeMark1 = iterator1.next();  
        	while (iterator2.hasNext()) {  
            	CodeMark codeMark2 = iterator2.next(); 
            	if (codeMark2.getCode().equals(codeMark1.getCode())) {  
            		//使用迭代器的删除方法删除  
            		iterator2.remove();
                } 
            }
        }  */
		List<String> list = new ArrayList<>();
		for(CodeMark cm : codeMarkList1){
			list.add(cm.getCode());
		}
		
		List<String> list5 = new ArrayList<>();
		for(CodeMark cm : codeMarkList2){
			list5.add(cm.getCode());
		}
		
		list5.removeAll(list);
		
		for (String  c4 : list5) {
			for (CodeMark c3 : codeMarkList3) {
				if (c4.equals(c3.getCode())) {
					flag=0;
					codeArr3 += c4 + ",";
				}
			}
		}
		if(flag==1) {
		
		// 连雷明 修改
		//替换条码
		//1.1、找到旧条码中第一个条码的位置
		CodeMark codeMark = cancellingStockDetailService.queryCodeByCode(codeMarkList1.get(0).getCode());
		String code = ","+codeMarkList1.get(0).getCode()+",";
		ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = ReceiveDetailService.queryMaterielTrayByCode(code);
		if(zcMaterielAndTrayEntity != null){
			
			//********************************************tdd************************************
			//现在条码
			List<CodeMark> codeMarkListX = codeMarkList2;
			//原有条码
			List<CodeMark> codeMarkListY = codeMarkList1;
			//现在条码比较原有条码新增
			List<CodeMark> codeMarkListXS = new ArrayList<>();
			
			for (int j = 0; j < codeMarkListY.size(); j++) {
				//在新条码中是否查询到此次循环旧条码 0 否 1是
				int flg = 0;
				for (int k = 0; k < codeMarkListX.size(); k++) {
					//此次循环新条码  == 此次循环旧条码
					if(codeMarkListX.get(k).getCode().equals(codeMarkListY.get(j).getCode())){
						//修改物料托盘信息
						ZcMaterielAndTrayEntity zcMaterielAndTrayEntity1 = ReceiveDetailService.queryMaterielTrayByCode(codeMarkListY.get(j).getCode());
						if(zcMaterielAndTrayEntity1 != null){
							int num = zcMaterielAndTrayEntity1.getmNum()-codeMarkListY.get(j).getNum()+codeMarkListX.get(k).getNum();
							inventoryService.updateById(zcMaterielAndTrayEntity1.getId()+"", "mNum", num+"", "zc_materiel_tray");
						}
						//修改记录
						//根据精准码查询是否存在
						CodeMark CodeMark = ReceiveDetailService.queryCodeMarkByCode(codeMarkListY.get(j));
						if (CodeMark != null) {
							ReceiveDetailService.updateCodeMark(codeMarkListX.get(k));
						} else {
							//绑定新条码
							ReceiveDetailService.addCodeMark(codeMarkListX.get(k));
						}
						flg = 1;
						break;
					}
				}
				//没有找到
				if(flg == 0){
					//删除托盘物料
					ZcMaterielAndTrayEntity zcMaterielAndTrayEntity1 = ReceiveDetailService.queryMaterielTrayByCode(codeMarkListY.get(j).getCode());
					if(zcMaterielAndTrayEntity1 != null){
						String mCode = zcMaterielAndTrayEntity1.getMateriel_code();
						//用空字符串替换旧条码
						String newCode2 = mCode.replace(codeMarkListY.get(j).getCode()+",", "");
						if(newCode2.length() == 0){
							//如果托盘空了，则删除这条数据(现在不能删，只有添加新条码后，再盘点托盘为空，进行删除，新条码有可能放回来)
							ReceiveDetailService.deleteMaterielTrayById(zcMaterielAndTrayEntity1.getId());
						}else{
							//把替换后的条码集合放回原来托盘
							ReceiveDetailService.updateMaterielTrayByCode(zcMaterielAndTrayEntity1.getId() + "", newCode2);
							//根据精准码查询是否存在
							CodeMark codeMark1 = ReceiveDetailService.queryCodeMarkByCode(codeMarkListY.get(j));
							if (codeMark1 != null) {
								inventoryService.updateById(zcMaterielAndTrayEntity1.getId()+"", "mNum", (zcMaterielAndTrayEntity1.getmNum()-codeMark.getNum())+"", "zc_materiel_tray");
							} 
						}
					}
					//删除记录
					stockOutService.deleteCodemarkOutByCode(codeMarkListY.get(j).getCode());
				}
			}
			
			for (int j = 0; j < codeMarkListX.size(); j++) {
				//在新条码中是否查询到此次循环旧条码 0 否 1是
				int flg = 0;
				for (int k = 0; k < codeMarkListY.size(); k++) {
					if(codeMarkListX.get(j).getCode().equals(codeMarkListY.get(k).getCode())){
						flg = 1;
						break;
					}
				}
				if(flg == 0){
					codeMarkListXS.add(codeMarkListX.get(j));
				}
			}
			if(codeMarkListXS.size() > 0){
				String codes = "";
				int sum = 0;
				for (CodeMark codeMark1 : codeMarkListXS) {
					codes += codeMark1.getCode() + ",";
					sum += codeMark1.getNum();
					//绑定新条码
					ReceiveDetailService.addCodeMark(codeMark1);
				}
				ZcMaterielAndTrayEntity zcMaterielAndTrayEntity1 = new ZcMaterielAndTrayEntity();
				zcMaterielAndTrayEntity1.setMid(zcMaterielAndTrayEntity.getMid());
				zcMaterielAndTrayEntity1.setmBatch(zcMaterielAndTrayEntity.getmBatch());
				zcMaterielAndTrayEntity1.setMateriel_code(codes);
				String tray_code = System.currentTimeMillis()+"";
				zcMaterielAndTrayEntity1.setTray_code(tray_code);
				zcMaterielAndTrayEntity1.setmNum(sum);
				
				//操作人姓名
				String username = workList.get(0).getWorkman();
				//根据员工姓名查询员工id
				Long uid = unpackDetalService.selectUidByUname(username);
				zcMaterielAndTrayEntity.setBinding_person(uid);
				
				zcMaterielAndTrayEntity1.setBinding_date(DateUtil.dateFormat1());
				inventoryService.MaterielTrayInsert(zcMaterielAndTrayEntity1);
				ZcTrayAndLocationEntity a = new ZcTrayAndLocationEntity();
				a.setLocation_code("HC");
				//根据库位查询
				ZcTrayAndLocationEntity zcTrayAndLocationEntityOld = zcBindAndUnbindService.selectTrayCodeByLocationCode(a);
				//3、如果不为空，修改数据
				if(zcTrayAndLocationEntityOld != null){
					String trayCodes = zcTrayAndLocationEntityOld.getTray_code() + zcMaterielAndTrayEntity1.getTray_code() + ",";
					inventoryService.updateById(zcTrayAndLocationEntityOld.getId()+"", "tray_code", trayCodes, "zc_tray_location");
				}else{
					//4、新增库位至待检区
					ZcTrayAndLocationEntity zcTrayAndLocationEntity = new ZcTrayAndLocationEntity();
					//托盘码
					zcTrayAndLocationEntity.setTray_code(tray_code);
					//库区编码
					zcTrayAndLocationEntity.setLocation_code("HC");
					//绑定人
					zcTrayAndLocationEntity.setBinding_person(zcMaterielAndTrayEntity1.getBinding_person());
		    		//绑定时间
					zcTrayAndLocationEntity.setBinding_date(zcMaterielAndTrayEntity1.getBinding_date());
					inventoryService.trayLocationInsert(zcTrayAndLocationEntity);
				}
			}
			//********************************************tdd************************************
			//2、遍历删除所有的旧条码
			/*for(CodeMark cm : codeMarkList1){
				//2.1查询条码的位置信息
				String code2 = ","+cm.getCode()+",";
				ZcMaterielAndTrayEntity zcMaterielAndTrayEntity2 = ReceiveDetailService.queryMaterielTrayByCode(code2);
				if(zcMaterielAndTrayEntity2 != null){
					String mCode = zcMaterielAndTrayEntity2.getMateriel_code();
					//2.2、用空字符串替换旧条码
					String newCode2 = mCode.replace(cm.getCode()+",", "");
					if(newCode2.length() == 0){
						//2.3.1、如果托盘空了，则删除这条数据(现在不能删，只有添加新条码后，再盘点托盘为空，进行删除，新条码有可能放回来)
						//ReceiveDetailService.deleteMaterielTrayById(zcMaterielAndTrayEntity2.getId());
					}else{
						//2.3.2、把替换后的条码集合放回原来托盘
						ReceiveDetailService.updateMaterielTrayByCode(zcMaterielAndTrayEntity2.getId() + "", newCode2);
						inventoryService.updateById(zcMaterielAndTrayEntity.getId()+"", "mNum", (zcMaterielAndTrayEntity.getmNum()-codeMark.getNum())+"", "zc_materiel_tray");
					}
				}
			}
			//1.2、把新条码拼接为字符串
			String codes = "";
			int sum = 0;
			for (CodeMark codeMark2 : codeMarkList2) {
				codes += codeMark2.getCode() + ",";
				CodeMark ck = cancellingStockDetailService.queryCodeByCode(codeMarkList1.get(0).getCode());
				sum += ck.getNum();
			}
			String materiel_code = zcMaterielAndTrayEntity.getMateriel_code();
			//1.3、用新条码集合替换旧条码
			//String newCode = materiel_code.replace(codeMarkList1.get(0).getCode()+",", codes);
			String newCode = materiel_code + codes;
			//1.4、把替换后的条码集合放回原来托盘
			ReceiveDetailService.updateMaterielTrayByCode(zcMaterielAndTrayEntity.getId() + "", newCode);
			inventoryService.updateById(zcMaterielAndTrayEntity.getId()+"", "mNum", (zcMaterielAndTrayEntity.getmNum() + codeMark.getNum())+"", "zc_materiel_tray");
			*///添加缓存区
			/*for (CodeMark codeMark : codeMarkList2) {
				codeArr2 += codeMark.getCode() + ",";
				//addStr += codeMark.getCode() + ",";
			}
			ReceiveDetailService.updateMaterielTrayByCode2(codeArr1, codeArr2);*/
			//Long uid = Long.parseLong(workList.get(0).getWorkman());
			Date date = new Date();
			DevaningLog dl = new DevaningLog();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String time = sdf.format(date);
			dl.setWork_time(time);
			SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss");
			String time2 = sdf2.format(date);
			dl.setNumber(time2);
			//dl.setUser_id(uid);
			
			//保存工作量
			DevaningWork dw = new DevaningWork();
			//dw.setUserId(uid);
			dw.setUserName(workList.get(0).getWorkman());
			dw.setLogNumber(time2);
			for(Workload work : workList){
				dw.setBoxQuantity(work.getGood_num());
				dw.setPcsQuantity(work.getNgood_num());
				devaningWorkService.insert(dw);
			}
			Long Receive_detail_id=codeMarkList1.get(0).getReceive_detail_id();
			
			ReceiveDetailQuality byCode = inventoryService.queryReceiveByCode(codeMarkList2.get(0).getCode());
			//1.遍历json1进行删除
			for (int i = 0; i < codeMarkList1.size(); i++) {
				dl.setDetail_id(Receive_detail_id);
				dl.setCode(codeMarkList1.get(i).getCode());
				dl.setQuantity(codeMarkList1.get(i).getNum());
				dl.setIs_ng(codeMarkList1.get(i).getIs_ng());
				dl.setStatus(0);
				
				//--------------给历史记录表插入数据--------------
				BarCodeOperation bar = new BarCodeOperation();
				Long id = barCodeOperationService.queryIdByName(workList.get(0).getWorkman());
				bar.setOperator(id);
				bar.setMaterielId(byCode.getMid());
				bar.setBatch(byCode.getPici());
				bar.setOperatingTime(time);
				bar.setType("拆箱前");
				bar.setResult("成功");
				bar.setBarCode(codeMarkList1.get(i).getCode());
				barCodeOperationService.insert(bar);
				//--------------给历史记录表插入数据--------------
				
				cancellingStockDetailService.insertDevaning(dl);
				//ReceiveDetailService.uncomeku(codeMarkList1.get(i).getCode());
			}
			//2.遍历json2进行增加
			for (int i = 0; i < codeMarkList2.size(); i++) {
				dl.setDetail_id(Receive_detail_id);
				dl.setCode(codeMarkList2.get(i).getCode());
				dl.setQuantity(codeMarkList2.get(i).getNum());
				dl.setIs_ng(codeMarkList2.get(i).getIs_ng());
				dl.setStatus(1);
				cancellingStockDetailService.insertDevaning(dl);
				//添加每种物料对应的多个条码
				//ReceiveDetailService.addCodeMark(codeMarkList2.get(i));
				
				//--------------给历史记录表插入数据--------------
				BarCodeOperation bar = new BarCodeOperation();
				Long id = barCodeOperationService.queryIdByName(workList.get(0).getWorkman());
				bar.setOperator(id);
				bar.setMaterielId(byCode.getMid());
				bar.setBatch(byCode.getPici());
				bar.setOperatingTime(time);
				bar.setType("拆箱后");
				bar.setResult("成功");
				bar.setBarCode(codeMarkList2.get(i).getCode());
				barCodeOperationService.insert(bar);
				//--------------给历史记录表插入数据--------------
			}
			if (codeMarkList1.size() > 0) {
				//传递数据到页面
				jsonObject.put("status", "1");
				jsonObject.put("message", "");
				jsonObject.put("data", "提交成功");
			}else {
				//传递数据到页面
				jsonObject.put("status", "0");
				jsonObject.put("message", "提交失败");
				jsonObject.put("data", "0");
			}
		}else{
			//传递数据到页面
			jsonObject.put("status", "0");
			jsonObject.put("message", "请扫正确条码");
			jsonObject.put("data", "0");
		}
		}else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "输入的条码"+codeArr3+"与原条码重复");
			jsonObject.put("data", "0");
			
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 根据精准码查询是否存在
	 * @param mcode
	 * @param response
	 */
	@RequestMapping("/queryRepeatAccurateByCodeApp")
	public void queryRepeatAccurateByCodeApp(String mcode, HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();
		CodeMark codemark = ReceiveDetailService.queryRepeatAccurateByCodeApp(mcode);
		if (codemark != null) {
			jsonObject.put("status", "0");
			jsonObject.put("message", "条码已使用");
			jsonObject.put("data", codemark.getCode());
		} else {
			jsonObject.put("status", "1");
			jsonObject.put("message", "");
			jsonObject.put("data", mcode);
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 查询有仓库操作员权限的人员
	 * @param mcode
	 * @param response
	 */
	@RequestMapping("/queryRoleUser")
	public void queryRoleUser(HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();
		List<String> userNmaeList = ReceiveDetailService.queryRoleUser();
		if (userNmaeList.size() > 0) {
			jsonObject.put("status", "1");
			jsonObject.put("message", "");
			jsonObject.put("data", userNmaeList);
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "查询数据为空");
			//jsonObject.put("data", "");
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 将入库后的不良品入库
	 * @param json
	 * @param person
	 * @param response
	 */
	@RequestMapping("/ngInstock")
	public void ngInstock(String json, String person, HttpServletResponse response) {
		BarCodeConversionRecord record = new BarCodeConversionRecord();
		Gson gson = new Gson();
		JSONObject jsonObject = new JSONObject();
		List<CodeMark> codeMarkList = gson.fromJson(json, new TypeToken<List<CodeMark>>() {}.getType());
		for (CodeMark codeMark : codeMarkList) {
			//如果是良品
			if (codeMark.getIs_ng() == 0) {
				Long affact = ReceiveDetailService.updateIsngStatus(codeMark.getCode());
				//根据条码查询物料和批次
				ReceiveDetailQuality receiveDetailQuality = ReceiveDetailService.queryReceiveDetailQualityByCode(codeMark.getCode());
				record.setMateriel_id(receiveDetailQuality.getMid());
				record.setMateriel_count(codeMark.getNum());
				record.setOperate_id(Long.parseLong(person));
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				record.setOperate_time(sdf.format(new Date()));
				record.setPrefix_code(codeMark.getCode());
				record.setOperate_type("良品转不良品");
				record.setTrans_reason("");
				record.setImg_url("");
				//新增条码转换记录
				ReceiveDetailService.insertBarCodeConversionRecord(record);
				if (affact > 0) {
					jsonObject.put("status", "1");
					jsonObject.put("data", "转换成功");
				} else {
					jsonObject.put("status", "0");
					jsonObject.put("message", "转换失败");
				}
			} else {
				//不良品转良品
				Long affact = ReceiveDetailService.updateIsngStatus1(codeMark.getCode());
				//根据条码查询物料和批次
				ReceiveDetailQuality receiveDetailQuality = ReceiveDetailService.queryReceiveDetailQualityByCode(codeMark.getCode());
				record.setMateriel_id(receiveDetailQuality.getMid());
				record.setMateriel_count(codeMark.getNum());
				record.setOperate_id(Long.parseLong(person));
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				record.setOperate_time(sdf.format(new Date()));
				record.setPrefix_code(codeMark.getCode());
				record.setOperate_type("不良品转良品");
				record.setTrans_reason("");
				record.setImg_url("");
				//新增条码转换记录
				ReceiveDetailService.insertBarCodeConversionRecord1(record);
				if (affact > 0) {
					jsonObject.put("status", "1");
					jsonObject.put("data", "转换成功");
				} else {
					jsonObject.put("status", "0");
					jsonObject.put("message", "转换失败");
				}
			}
			try {
				ResponseUtil.write(response, jsonObject);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}
	
	/**
	 * 良品不良品转换
	 * @param json
	 * @param person
	 * @param response
	 */
	@RequestMapping("/transCodeMarkStatus")
	public void transCodeMarkStatus(String json, String person, HttpServletResponse response) {
		Gson gson = new Gson();
		List<CodeMark> codeMarkList = gson.fromJson(json, new TypeToken<List<CodeMark>>() {}.getType());
		for (CodeMark codeMark : codeMarkList) {
			//根据条码修改条码状态
			Long affact = ReceiveDetailService.updateIsngStatus(codeMark.getCode());
			/*if (affact > 0) {
				//根据条码查询物料和批次
				ReceiveDetailQuality receiveDetailQuality = ReceiveDetailService.queryReceiveDetailQualityByCode(codeMark.getCode());
				//1.首先去查询不良品库中该物料是否存在
				ZcRejectsWarehouseEntity zcRejectsWarehouseEntity = ReceiveDetailService.
						queryZcRejectsWarehouseEntityByMbatchAngMid(receiveDetailQuality);
				//如果存在
				if (zcRejectsWarehouseEntity != null) {
					int totality = zcRejectsWarehouseEntity.getTotality();
					totality = receiveDetailQuality.getNg_num() + totality;
					receiveDetailQuality.setNg_num(totality);
					ReceiveDetailService.updateZcRejectsWarehouseEntity(receiveDetailQuality);
				} else {
					receiveDetailQuality.setPerson(person);
					ReceiveDetailService.addZcRejectsWarehouseEntity(receiveDetailQuality);
				}
			}*/
		}
		JSONObject jsonObject = new JSONObject();
		List<String> userNmaeList = ReceiveDetailService.queryRoleUser();
		if (userNmaeList.size() > 0) {
			jsonObject.put("status", "1");
			jsonObject.put("message", "");
			jsonObject.put("data", "不良品入库成功");
		} else {
			jsonObject.put("status", "0");
			jsonObject.put("message", "不良品入库失败");
			jsonObject.put("data", "");
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 查询状态为0的计数入库单
	 * @param response
	 */
	@RequestMapping("selectAllReceipt")
	public void selectAllReceipt(HttpServletResponse response){
		ZcGeneralQueryEntity zcGeneralQueryEntity = new ZcGeneralQueryEntity();
		//未收货
		List<Receive> list = zcSimplificationInService.selectSimplificationInListAll(zcGeneralQueryEntity);
		
		JSONObject jsonObject = new JSONObject();
		int count = list.size();
		if (count>0) {
			//传递数据到页面
		    jsonObject.put("status", "1");
		    jsonObject.put("message", "");
		    jsonObject.put("data", list);
		}else {
			//传递数据到页面
		    jsonObject.put("status", "0");
		    jsonObject.put("message", "查询数据为空");
		    jsonObject.put("data", list);
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 通过收货单号查详情（计数）
	 */
	@RequestMapping("selectReceiptDtailByNumber")
	public void selectReceiptDtailByNumber(String receiveNumber,HttpServletResponse response){
		ReceiveDetail param = new ReceiveDetail();
		param.setReceiveNumber(receiveNumber);
		List<ReceiveDetail> list = ReceiveDetailService.queryAllByMution(param );
		
		JSONObject jsonObject = new JSONObject();
		int count = list.size();
		if (count > 0) {
			//传递数据到页面
		    jsonObject.put("status", "1");
		    jsonObject.put("message", "");
		    jsonObject.put("data", list);
		}else {
			//传递数据到页面
		    jsonObject.put("status", "0");
		    jsonObject.put("message", "查询数据为空");
		    jsonObject.put("data", list);
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 收货提交(计数)
	 * @param Details 收货详情集合
	 * @param person 收货人
	 * @param sure_name 回收容器数量
	 * @param response 响应
	 * @throws Exception 异常
	 */
	@RequestMapping("/submitReceipt")
	public void submitReceipt(String Details, String person, String sure_name, HttpServletResponse response) throws Exception{
		//初始化影响行数
		int affact1 = 0;
		Long affact = 0L;
		//json参数转化为实体集合
		Gson gson = new Gson();
		List<ReceiveDetail> receiveDetailList = gson.fromJson(Details, new TypeToken<List<ReceiveDetail>>() {}.getType());
		//遍历修改
		for (ReceiveDetail receiveDetail : receiveDetailList) {
			/*==================新表添加数据================*/
			//ReceiveDetailService.addReceiveDetailInstock(receiveDetail);
			/*==================修改收货详细表信息==========*/
			affact1 = ReceiveDetailService.update(receiveDetail);
			/*==================修改质检表信息==========*/
			//ReceiveDetailService.updateReceiveDetailQuality(receiveDetail);
			/*====================添加库存=======================*/
			int number = receiveDetail.getCodeNum();
			ZcInventoryInfoEntity zcInventoryInfoEntity = upService.selectByMid2(receiveDetail.getMid() + "", receiveDetail.getPici());
			//1.如果查到
			if (zcInventoryInfoEntity != null) {
				int mNum = zcInventoryInfoEntity.getmNum();
				//1.如果是精准码,只存入总数
				mNum = number + mNum;
				//总数量（个数）
				zcInventoryInfoEntity.setmNum(mNum);
				affact = upService.editStockOnlyCount(zcInventoryInfoEntity);
			} else {
				ZcInventoryInfoEntity zcInventoryInfoEntity1 = new ZcInventoryInfoEntity();
				zcInventoryInfoEntity1.setMid(receiveDetail.getMid());
				zcInventoryInfoEntity1.setmNum(receiveDetail.getCodeNum());
				zcInventoryInfoEntity1.setmBatch(receiveDetail.getPici());
				zcInventoryInfoEntity1.setEnterPerson(Long.parseLong(person));
				affact = upService.insertStockOnlyCount(zcInventoryInfoEntity1);
			}
		}

		//获取收货单号
		ReceiveDetail receiveDetail = receiveDetailList.get(0);
		//更改一级状态  --为已收货
		Receive receive = new Receive();
		receive.setReceiveNumber(receiveDetail.getReceiveNumber());
		receive.setIsSimple(1);
		List<Receive> receives = ReceiveService.allByMution(receive);
		
		if(receives.size()  > 0) {
			Receive receive2 = receives.get(0);
			receive2.setState(1);
			receive2.setReceiveDate(DateUtil.dateFormat1());
			receive2.setReceiveName(person);
			receive2.setSendCompany(null);
			//回收容器数量
			receive2.setSureName(sure_name);
			ReceiveService.update(receive2);
		}
		JSONObject jsonObject = new JSONObject();
		if (affact > 0) {
			//传递数据到页面
		    jsonObject.put("status", "1");
		    jsonObject.put("message", "");
		    jsonObject.put("data", "提交成功");
		}else {
			//传递数据到页面
		    jsonObject.put("status", "0");
		    jsonObject.put("message", "提交失败");
		    jsonObject.put("data", "0");
		}
		ResponseUtil.write(response, jsonObject);
	}
	
	/**
	 * 根据收货单单号查询所有ReceiveMark实体
	 * @param receiveId 收货单id
	 * @param mcode
	 * @param response
	 */
	@RequestMapping("/queryReceiveCodeByReceiveId")
	public void queryReceiveCodeByReceiveId(String receiveId, String mcode, HttpServletResponse response){
		CodeMark codeMark1 = new CodeMark();
		codeMark1.setCode(mcode);
		//1.先查询CodeMark，如果查到直接返回此条码已收货
		//2.先查询CodeMark，如果未查到，再去查ReceiveMark，还没查到，返回app"此条码不存在"
		//3.先查询CodeMark，如果未查到，再去查ReceiveMark，查到，返回ReceiveMark实体
		JSONObject jsonObject = new JSONObject();
		//根据条码查询CodeMark实体
		CodeMark codeMark = ReceiveDetailService.queryCodeMarkByCode(codeMark1);
		if (codeMark != null) {
			//传递数据到页面
		    jsonObject.put("status", "0");
		    jsonObject.put("message", "此物料已收货");
		} else {
			//根据收货单单号和条码查询ReceiveMark实体
			ReceiveMark receiveMark = ReceiveDetailService.queryReceiveCodeByReceiveId(receiveId, mcode);
			if (receiveMark != null) {
				//传递数据到页面
			    jsonObject.put("status", "1");
			    jsonObject.put("data", receiveMark);
			} else {
				//传递数据到页面
			    jsonObject.put("status", "0");
			    jsonObject.put("message", "此条码不存在");
			}
		}
		
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 添加错误信息到错误信息表
	 */
	@RequestMapping("error.do")
	public void addError(String error_type, String error_message, HttpServletResponse response) {
		int affct = 0;
		ErrorJyy errorJyy = new ErrorJyy();
		errorJyy.setError_time(DateUtil.dateFormat3());
		errorJyy.setError_message(error_message);
		errorJyy.setError_type(error_type);
		
		affct = errorServise.addError(errorJyy);
		
		JSONObject jsonObject = new JSONObject();
		if (affct > 0) {
			//传递数据到页面
		    jsonObject.put("status", "1");
		    jsonObject.put("message", "");
		    jsonObject.put("data", "提交成功");
		}else {
			//传递数据到页面
		    jsonObject.put("status", "0");
		    jsonObject.put("message", "提交失败");
		    jsonObject.put("data", "0");
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 分页查询条码转换记录
	 * @param response
	 * @param criteria
	 */
	@RequestMapping("/queryBarCodeConversionRecordCriteria")
	public void queryBarCodeConversionRecordCriteria(HttpServletResponse response, LzQueryCriteria criteria){
		List<BarCodeConversionRecord> recordList = ReceiveDetailService.queryBarCodeConversionRecordCriteria(criteria);
		int count = ReceiveDetailService.countBarCodeConversionRecordCriteria(criteria);
		JSONObject jsonObject = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(recordList);
		jsonObject.put("code", 0);
		jsonObject.put("data", jsonArray);
		jsonObject.put("count", count);
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 良品转不良品确认
	 * @param response
	 */
	@RequestMapping("/updateConfirm")
	public void updateConfirm(HttpServletResponse response, String id){
		Long affectRow = ReceiveDetailService.updateConfirm(Long.parseLong(id));
		if (affectRow > 0) {
			try {
				ResponseUtil.write(response, affectRow);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			try {
				ResponseUtil.write(response, 0);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 查询条码是否存在
	 * @param response
	 * @param code 条码
	 */
	@RequestMapping("/queryLifeByCode")
	public void queryLifeByCode(HttpServletResponse response, String code){
		JSONObject jsonObject = new JSONObject();
		CodeMark codeMark = new CodeMark();
		codeMark.setCode(code);
		//根据条码查询CodeMark实体
		CodeMark cm = ReceiveDetailService.queryCodeMarkByCode(codeMark);
		if (cm == null) {
			//传递数据到页面
		    jsonObject.put("status", "1");
		    jsonObject.put("data", code);
		} else {
			//传递数据到页面
		    jsonObject.put("status", "0");
		    jsonObject.put("message", "此条码已存在");
		}
		try {
			ResponseUtil.write(response, jsonObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
